#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;

void mouseHandler(int event, int x, int y, int flafs, void* userData) {
    if (event == cv::EVENT_LBUTTONUP) {
        // click
        cout << "(x,y) = (" << x << ", " << y << ")" << endl;
        cv::Point* pos = static_cast<cv::Point*>(userData);
        pos->x = x;
        pos->y = y;
    }
}


int main(int argc, char** argv) {
    if (argc < 2) {
        cout << "\nError: You had too few parameters.\n" << endl;
        return -1;
    }

    cv::Mat img = cv::imread(argv[1]);
    if (img.empty()) {
        cout << "Could not open " << argv[1] << endl;
        return 1;
    }
    cv::Point last_pos,m_pos(-1,-1);
    cv::namedWindow("Image", cv::WINDOW_AUTOSIZE);
    cv::setMouseCallback("Image", mouseHandler, &m_pos);

    cv::Mat img_show;
    cv::Vec3b color;
    img.copyTo(img_show);
    while(1) {
        if(m_pos.x > 0 && m_pos.y > 0 && !(m_pos.x == last_pos.x && m_pos.y == last_pos.y)) {
            cout << "main(x,y) = (" << m_pos.x << ", " << m_pos.y << ")" << endl;
            last_pos.x = m_pos.x; last_pos.y = m_pos.y;
            img.copyTo(img_show);
            color = img.at<cv::Vec3b>(m_pos.y, m_pos.x);
            stringstream text;
            // cout << "value:" << (int)color[0] << ", " << color[1] << ", " << color[2] << endl;
            text << "(" << (ushort)color[0] << "," << (ushort)color[1] << "," << (ushort)color[2] << ")";
            cv::putText(img_show, text.str(), m_pos, cv::FONT_HERSHEY_DUPLEX, 1.0f, CV_RGB(255, 0, 0));
        }
        cv::imshow("Image", img_show);
        if ((cv::waitKey(33) & 255) == 27)
            break;
    }
    
    
    // hold mouse event
    

    cv::waitKey();
    cv::destroyWindow("Image");
    return 0;
}